<template>
    <div class="form-main">
        <el-page-header :content="route.params.id?'修改文章':'添加文章'" @back="closeTab"></el-page-header>
        <div class="form-content">
            <el-form :model="formData" ref="formRef" label-width="100px">
                <el-form-item label="分类" prop="classify" :rules="[{required: true,message: '请选择分类',trigger: 'blur',type:'number'}]">
                    <el-cascader v-model="pids" :options="classifyTreeList" :props="{checkStrictly: true,value:'id',label:'name'}" placeholder="请选择分类" @change="pidChange"/>
                </el-form-item>    
                <el-form-item label="标题" prop="title" :rules="[{required: true,message: '请输入标题',trigger: 'blur'}]">
                    <el-input v-model="formData.title" placeholder="请输入标题"/>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="formData.desc" type="textarea" :rows="4" placeholder="请输入描述"/>
                </el-form-item>
                <el-form-item label="标签">
                    <el-select
                        class="multiple-select"
                        style="width:400px;"
                        v-model="formData.tags"
                        multiple
                        filterable
                        placeholder="文章标签">
                        <el-option
                            v-for="item in tagList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="封面">
                    <uploadimg dir="article_cover" v-model="formData.cover"/>
                </el-form-item>
                <el-form-item label="排序值" prop="sort" :rules="[{required: true,message: '请输入排序值',trigger: 'blur'}]">
                    <el-input-number v-model="formData.sort" />
                </el-form-item>
                <el-form-item label="状态" prop="status" :rules="[{required: true,message: '请选择状态',trigger: 'blur',type:'number'}]">
                    <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
                </el-form-item>
                <el-form-item label="内容" prop="content" :rules="[{required: true,message: '请输入内容',trigger: 'blur'}]">
                    <editor img-dir="article_content" v-model="formData.content"></editor>
                </el-form-item>
                <el-form-item>
                    <el-button class="form-submit-btn" type="primary" :loading="loading" @click="handleSubmit(formRef)">提交</el-button>
                </el-form-item> 
            </el-form>
        </div>
    </div>    
</template>



<script setup lang="ts">
import {ref,unref} from 'vue'
import { ElForm, ElNotification } from 'element-plus'
import { add,edit,detail } from '/@/api/article'
import { list as classifyListApi } from '/@/api/classify'
import { page as tagListApi } from '/@/api/tag'
import uploadimg from '/@/components/uploadimg/index.vue'
import {formData as formDataType} from './type'
import {classify} from '../classify/type'
import {tag} from '../tag/type'
import { useRoute } from 'vue-router'
import useCloseTab from '/@/hooks/useCloseTab'
import editor from '/@/components/editor/index.vue'
const route = useRoute()
const formRef = ref()
const loading = ref(false)
const formData = ref<formDataType>({
  classify: '',
  content: '',
  cover: '',
  desc: '',
  sort: 0,
  status: 1,
  tags: [],
  title: ''
})
let classifyList:classify[] = []
const classifyTreeList = ref<classify[]>([])
const pids = ref<number[]>([])
const tagList = ref<tag[]>([])
const { closeTab } = useCloseTab()

const getDetail = async () => {
    const {data} = await detail(Number(route.params.id))
    const arr:number[] = []
    const tags = []
    for(const i of data.tags) {
        tags.push(i.id)
    }
    data.tags = tags
    formData.value = data
    getPidValue(arr,classifyList,data.classify.id)
    formData.value.classify = data.classify.id
    pids.value = arr
}

const getPidValue = (arr:number[],list:classify[],pid:number) => {
  for(let i of list){
      if(i.id === pid){
          arr.unshift(i.id);
          getPidValue(arr,list,i.pid);
      }
  }
}

const doTree = (arr:classify[],list:classify[],pid:number) => {
  for(let i of list){
    if(i.pid === pid){
      i.children = []
      arr.push(i)
      doTree(i.children,list,i.id)
    }
  }
}

const getClassifyList = async () => {
  const {data} = await classifyListApi()
  classifyList = data
  const list:classify[] = []
  doTree(list,data,0)
  classifyTreeList.value = list
}

const getTagList = async () => {
    const {data} = await tagListApi()
    tagList.value = data
}

const pidChange = (ids:number[]) => {
  formData.value.classify = ids[ids.length-1]
}

const handleSubmit = (formEl: InstanceType<typeof ElForm> | undefined) => {
   if (!formEl) return
   formEl.validate(async (valid) => {
   if (valid) {
      loading.value = true
      try{
         const req = unref(formData)
         if(route.params.id){
            await edit(Number(route.params.id),req)
         }else{
            await add(req)
         }
         ElNotification({
            type: 'success',
            message: '提交成功'
         })
         closeTab()
      }finally{
         loading.value = false  
      }     
    }
  })
}

const init = async () => {
    await Promise.all([
        getClassifyList(),
        getTagList()
    ])
    if(route.params.id){
        getDetail()
    }
}

init()

</script>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
    name: 'article-form',
})
</script>

<style scoped lang="scss">

</style>